<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="业务员" prop="salesmanUserIds">
            <el-input
                v-model="queryParams.salesmanUserIds"
                placeholder="业务员"
                clearable
                @keyup.enter.native="handleQuery"
            />
        </el-form-item> -->
      <el-form-item label-width="60" label="业务员" prop="salesmanUserIds">
        <el-select
          v-model="queryParams.salesmanUserIds"
          placeholder="请输入名称搜索"
        >
          <el-option
            v-for="item in salesmanUserSearchList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label-width="100px"
        label="合同主体公司"
        prop="subjectFirmId"
      >
        <el-select
          v-model="queryParams.subjectFirmId"
          placeholder="请输入名称搜索"
        >
          <el-option
            v-for="item in subjectFirmList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工程类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option label="请选择" :value="null"></el-option>
          <el-option label="民建" :value="1"></el-option>
          <el-option label="市政" :value="2"></el-option>
          <el-option label="水利" :value="3"></el-option>
          <el-option label="公路" :value="4"></el-option>
          <el-option label="铁路" :value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="40" label="ID" prop="id">
        <el-input
          type="number"
          v-model="queryParams.id"
          placeholder="ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工程名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入工程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:engineering:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :height="divHeight"
      v-loading="loading"
      :data="engineeringList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" width="55" align="center" />
      <el-table-column fixed label="ID" width="55" align="center" prop="id" />
      <el-table-column
        fixed
        show-overflow-tooltip
        label="工程名称"
        align="center"
        prop="name"
      />
      <el-table-column label="编号" align="center" width="110"  prop="projectNo" show-overflow-tooltip />
      <el-table-column label="客户名称" align="center" prop="customUserName" show-overflow-tooltip/>
      <el-table-column
        show-overflow-tooltip
        label="施工单位"
        align="center"
        prop="constructionUnit"
      />
      <el-table-column label="施工地点" align="center" prop="address" show-overflow-tooltip/>
      <el-table-column label="运输距离km" align="center" width="110" prop="transport"  show-overflow-tooltip/>
      <el-table-column label="工程类型" align="center" prop="type" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">民建</span>
          <span v-if="scope.row.type == 2">市政</span>
          <span v-if="scope.row.type == 3">水利</span>
          <span v-if="scope.row.type == 4">公路</span>
          <span v-if="scope.row.type == 5">铁路</span>
        </template>
      </el-table-column>
      <el-table-column
        label="合同主体公司"
        align="center"
        width="120" 
        prop="subjectFirmName"
        show-overflow-tooltip
      />
      <el-table-column
        width="100"
        label="业务员"
        align="center"
        prop="salesmanUserIds"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ getName(scope.row.salesmanUserList) }}
        </template>
      </el-table-column>
      <el-table-column
        width="160"
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:engineering:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:engineering:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改营销中心--工程对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-card>
          <div slot="header" class="clearfix">
            <span>客户信息</span>
          </div>
          <el-form-item label="客户名称" :rules="[{ required: true, message: '请选择客户名称', trigger: 'change' }]" prop="customUserId">
            <div style="display: flex; gap: 20px; align-items: center">
              <span v-if="form.customUserName">{{ form.customUserName }}</span>
              <span v-if="form.userProperty">
                <span style="color: #606266; font-weight: bold"
                  >客户类型：</span
                >
                <span v-if="form.userProperty == 3">企业</span>
                <span v-if="form.userProperty == 4">个人</span>
              </span>
              <span v-if="form.customUserId"
                ><span style="color: #606266; font-weight: bold">客户ID：</span>
                {{ form.customUserId }}</span
              >
              <el-button type="text" @click.native="handleSelectName">{{
                form.customUserName ? "请重新选择" : "请选择"
              }}</el-button>
            </div>
          </el-form-item>
        </el-card>
        <el-card style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>工程信息</span>
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请输入工程名称', trigger: 'blur' }]"
                label="工程名称"
                prop="name"
              >
                <el-input v-model="form.name" placeholder="请输入工程名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请选择工程类型', trigger: 'blur' }]"
                label="工程类型"
                prop="type"
              >
                <el-select style="width:100%" v-model="form.type" placeholder="请选择">
                  <el-option label="民建" :value="1"></el-option>
                  <el-option label="市政" :value="2"></el-option>
                  <el-option label="水利" :value="3"></el-option>
                  <el-option label="公路" :value="4"></el-option>
                  <el-option label="铁路" :value="5"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <NumberFormItem
                errorTip="运输距离不能为负数"
                requiredMessage="请输入运输距离"
                label="运输距离(KM)"
                labelWidth="130px"
                prop="transport"
              >
                <el-input
                  type="number"
                  v-model="form.transport"
                  placeholder="请输入运输距离"
                />
              </NumberFormItem>
            </el-col>

            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请输入施工单位', trigger: 'blur' }]"
                label="施工单位"
                prop="constructionUnit"
              >
                <el-input
                  v-model="form.constructionUnit"
                  placeholder="请输入施工单位"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            :rules="[{ required: true, message: '请填写企业地址', trigger: 'blur' }]"
            label="企业地址"
          >
            <div style="display: flex; gap: 20px">
              <el-form-item
                :rules="[
                  { required: true, message: '请选择省份', trigger: 'change' },
                ]"
                prop="province"
              >
                <el-select
                  v-model="form.province"
                  @change="changePro"
                  placeholder="省份"
                >
                  <el-option
                    v-for="(value, key) in areaList.province_list"
                    :key="key"
                    :label="value"
                    :value="key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                :rules="[
                  { required: true, message: '请选择市', trigger: 'change' },
                ]"
                prop="city"
              >
                <el-select
                  v-model="form.city"
                  @change="changeCity"
                  placeholder="市"
                >
                  <el-option
                    v-for="(value, key) in cityList"
                    :key="key"
                    :label="value"
                    :value="key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                :rules="[
                  { required: true, message: '请选择区/县', trigger: 'change' },
                ]"
                prop="ward"
              >
                <el-select v-model="form.ward" placeholder="区/县">
                  <el-option
                    v-for="(value, key) in districtList"
                    :key="key"
                    :label="value"
                    :value="key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                style="width: 500px"
                :rules="[
                  { required: true, message: '请填写详细地址', trigger: 'blur' },
                ]"
                prop="address"
              >
                <el-input v-model="form.address" placeholder="详细地址" />
              </el-form-item>
            </div>
          </el-form-item>

          <el-row>
            <el-col :span="3">
              <el-form-item
                required
                label="付款人"
              >
              </el-form-item>
            </el-col>
            <el-col :span="6" style="margin-left: 17px">
              <el-form-item
                :rules="[
                  { required: true, message: '请填写姓名', trigger: 'blur' },
                ]"
                label-width="0px"
                prop="payerName"
              >
                <el-input v-model="form.payerName" placeholder="请填写姓名" />
              </el-form-item>
            </el-col>
            <el-col style="margin-left: 20px" :span="6">
              <el-form-item
                :rules="[
                  { required: true, message: '请填写手机号', trigger: 'blur' },
                  {
                    validator: validatorPhone,
                    trigger: 'blur',
                  },
                ]"
                label-width="0px"
                prop="payerPhone"
              >
                <el-input
                  v-model="form.payerPhone"
                  placeholder="请填写手机号"
                />
              </el-form-item>
            </el-col>
            <el-col :offset="1" :span="6">
              <div style="height: 36px; display: flex; align-items: center">
                <el-link @click="paymentVisible = true" type="primary"
                  >选择历史付款人</el-link
                >
              </div>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in form.personList" :key="index">
            <el-col :span="3">
              <el-form-item
                required
                label="现场联系人"
              ></el-form-item>
            </el-col>
            <el-col :span="5" style="margin-left: 17px">
              <el-form-item label-width="0px" 
              :rules="[
                  { required: true, message: '请填写现场联系人姓名', trigger: 'blur' },
                ]"
                :prop="'personList.' + index +'.name'"
                >
                <el-input v-model="item.name" placeholder="请填写姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="5" style="margin-left: 20px">
              <el-form-item
                :rules="[
                  {
                    validator: validatorPhone,
                    trigger: 'blur',
                  },
                ]"
                label-width="0px"
                :prop="'personList[' + index + '].phone'"
              >
                <el-input v-model="item.phone" placeholder="请填写手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="5" style="margin-left: 20px">
              <el-form-item
                :rules="[
                  {
                    validator: validatorPhone,
                    trigger: 'blur',
                  },
                ]"
                label-width="0px"
                :prop="'personList[' + index + '].phoneTwo'"
              >
                <el-input v-model="item.phoneTwo" placeholder="第二联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="3" style="margin-left: 20px">
              <div style="height: 36px; display: flex; align-items: center">
                <el-button
                  @click="deletePersonList(index)"
                  type="primary"
                  size="mini"
                  icon="el-icon-delete"
                  circle
                ></el-button>
                <el-button
                  v-if="index == form.personList.length - 1"
                  @click="addPersonList"
                  type="success"
                  size="mini"
                  icon="el-icon-plus"
                  circle
                ></el-button>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card style="margin-top: 20px" v-if="form.salesmanUserList">
          <div slot="header" class="clearfix">
            <span>我方信息</span>
          </div>
          <el-form-item
            label-width="100px"
            label="我司业务员"
            :rules="[
                  { required: true, message: '请选择我司业务员', trigger: 'change' },
                ]"
            prop="salesmanUserIds"
          >
            <div style="display: flex; gap: 20px; align-items: center">
              <span v-if="form.salesmanUserList.length > 0">{{
                showName
              }}</span>
              <el-button type="text" @click="selectNameVisible = true">{{
                form.salesmanUserIds ? "请重新选择" : "请选择"
              }}</el-button>
            </div>
          </el-form-item>
        </el-card>

        <el-card style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectCustomDialog
      :dialogVisible="dialogVisible"
      :multiple="false"
      @onClose="dialogVisible = false"
      @onSubmit="handleOnSubmit"
    ></SelectCustomDialog>
    <SelectPaymentDialog
      :dialogVisible="paymentVisible"
      @onClose="paymentVisible = false"
      @onSubmit="handleOnPaymentSubmit"
    ></SelectPaymentDialog>
    <SelectSalesmanDialog
    :styleOptions="{
          btnAlign:true,
          inputStyle:{
            width:'240px'
          },
          labelWidth:' '
        }"
      :dialogVisible="selectNameVisible"
      :disabledSearchFieldList="['principalPhone']"
      :defauleUser="
        (form.salesmanUserList || []).map((row) => ({
          userId: row.userId,
          userName: row.userName,
          nickName: row.nickName,
        }))
      "
      idName="userId"
      @onClose="selectNameVisible = false"
      @onSubmit="selectName"
    ></SelectSalesmanDialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import { listFirm } from "@/api/service/marketing/firm";
import {
  listEngineering,
  getEngineering,
  delEngineering,
  addEngineering,
  updateEngineering,
} from "@/api/service/marketing/engineering";
import SelectCustomDialog from "@/components/SelectDialog/SelectCustomDialog";
import SelectSalesmanDialog from "@/components/SelectDialog/SelectSalesmanDialog";
import SelectPaymentDialog from "@/components/SelectDialog/SelectPaymentDialog";
import { areaList } from "@vant/area-data";
import { isValidPhoneNumber } from "@/utils/validate";
import NumberFormItem from "@/components/NumberFormItem"
export default {
  name: "Engineering",
  components: {
    NumberFormItem,
    SelectCustomDialog,
    SelectSalesmanDialog,
    SelectPaymentDialog,
  },
  data() {
    const validatorPhone = (rule, value, callback) => {
      if (value) {
        if (!isValidPhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };

    return {
      divHeight:100,
      validatorPhone,
      areaList,
      selectNameVisible: false,
      dialogVisible: false,
      paymentVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营销中心--工程表格数据
      engineeringList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        customUserName: null,
        id: null,
        name: null,
        type: null,
        province: null,
        city: null,
        ward: null,
        address: null,
        transport: null,
        constructionUnit: null,
        payerName: null,
        payerPhone: null,
        salesmanUserIds: null,
        projectNo: null,
        subjectFirmId: null
      },
      // 远程搜索业务员结果
      salesmanUserLoading: false,
      salesmanUserSearchList: [],
      // 合同公司搜索结果
      subjectFirmLoading: false,
      subjectFirmList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
    };
  },
  computed: {
    showName() {
      if (this.form.salesmanUserList && this.form.salesmanUserList.length > 0) {
        return this.form.salesmanUserList
          .map((item) => item.nickName)
          .join(",");
      } else {
        return "";
      }
    },
    cityList() {
      const result = {};
      if (this.form.province) {
        Object.keys(this.areaList.city_list).forEach((key) => {
          if (+this.form.province < +key && +this.form.province + 10000 > key) {
            result[key] = this.areaList.city_list[key];
          }
        });
      }
      return result;
    },
    districtList() {
      const result = {};
      if (this.form.city) {
        Object.keys(this.areaList.county_list).forEach((key) => {
          if (+this.form.city < +key && +this.form.city + 100 > key) {
            result[key] = this.areaList.county_list[key];
          }
        });
      }
      return result;
    },
  },
  created() {
    this.divHeight = window.innerHeight - 300;
    this.getList();
    this.subjectFirmRemoteMethod()
    this.remoteMethod()
  },
  methods: {
    async subjectFirmRemoteMethod(query) {
      //this.queryParams.subjectFirmId = null
      const res = await listFirm({
          name: query,
          pageNum: 1,
          // pageSize: ,
        });
        // this.subjectFirmLoading = false;
        this.subjectFirmList = res.rows;

      // if (query !== "") {
      //   this.subjectFirmLoading = true;
      //   const res = await listFirm({
      //     name: query,
      //     pageNum: 1,
      //     pageSize: 5,
      //   });
      //   this.subjectFirmLoading = false;
      //   this.subjectFirmList = res.rows;
      // } else {
      //   this.subjectFirmList = [];
      // }
    },
    async remoteMethod(query) {
      const res = await listUser({
          userType: 1,
          roleCodeList: "business_role",
          nickName: query,
          pageNum: 1,
          // pageSize: 5,
        });
        // this.subjectFirmLoading = false;
        this.salesmanUserSearchList = res.rows;
      // //this.queryParams.salesmanUserIds = null
      // if (query !== "") {
      //   this.subjectFirmLoading = true;
      //   const res = await listUser({
      //     userType: 1,
      //     roleCodeList: "business_role",
      //     nickName: query,
      //     pageNum: 1,
      //     pageSize: 5,
      //   });
      //   this.subjectFirmLoading = false;
      //   this.salesmanUserSearchList = res.rows;
      // } else {
      //   this.salesmanUserSearchList = [];
      // }
    },
    getName(list) {
      if (list && list.length > 0) {
        return list.map((item) => item.nickName).join(",");
      } else {
        return "";
      }
    },
    handleOnPaymentSubmit(row) {
      this.form.payerName = row.name;
      this.form.payerPhone = row.phone;
    },
    deletePersonList(index) {
      this.form.personList.splice(index, 1);
    },
    addPersonList() {
      this.form.personList.push({
        name: '',
        phone: '',
        phoneTwo: '',
      });
    },
    selectName(arr) {
      this.form.salesmanUserList = arr.map((row) => ({
        userId: row.userId,
        userName: row.userName,
        nickName: row.nickName,
      }));
      this.form.salesmanUserIds = this.form.salesmanUserList
        .map((item) => item.userId)
        .join(",");
    },
    changePro() {
      this.form.city = null;
      this.form.ward = null;
    },
    changeCity() {
      this.form.ward = null;
    },
    handleSelectName() {
      this.dialogVisible = true;
    },
    handleOnSubmit(row) {
      this.form.customUserId = row.userInfoId;
      this.form.customUserName = row.principalName;
      this.form.userProperty = row.userProperty;
    },
    /** 查询营销中心--工程列表 */
    getList() {
      this.loading = true;
      listEngineering(this.queryParams).then((response) => {
        this.engineeringList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customUserId: null,
        customUserName: null,
        userProperty: null,
        name: null,
        type: null,
        province: null,
        city: null,
        ward: null,
        address: null,
        transport: null,
        personList: [
          {
            name: null,
            phone: null,
            phoneTwo: null,
          },
        ],
        salesmanUserList: [],
        constructionUnit: null,
        payerName: null,
        payerPhone: null,
        salesmanUserIds: null,
        projectNo: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增工程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEngineering(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateEngineering(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEngineering(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除营销中心--工程编号为"' + ids + '"的数据项？')
        .then(function () {
          return delEngineering(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/engineering/export",
        {
          ...this.queryParams,
        },
        `engineering_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container{
  overflow: hidden;
}
::v-deep .el-tabs__content {
  max-height: 500px;
  overflow: auto;
}
::v-deep .el-dialog__body {
  max-height: 700px;
  overflow: auto;
}
</style>